package redis_store

import (
	"github.com/gomodule/redigo/redis"
	"github.com/pelletier/go-toml"
	"go_oauth2/config"
	"time"
)

type RedisStore struct {
	pool *redis.Pool
}

func New(storeType string) *RedisStore {
	redisConfig := config.Config.Get(storeType).(*toml.Tree)
	return &RedisStore{&redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			return redis.Dial(
				redisConfig.Get("network").(string),
				redisConfig.Get("address").(string),
			)
		},
	}}
}

func (r *RedisStore) Find(token string) (b []byte, exists bool, err error) {
	conn := r.pool.Get()
	defer conn.Close()

	b, err = redis.Bytes(conn.Do("GET", token))
	if err == redis.ErrNil {
		return nil, false, nil
	} else if err != nil {
		return nil, false, err
	}
	return b, true, nil
}

func (r *RedisStore) Save(token string, b []byte) error {
	conn := r.pool.Get()
	defer conn.Close()

	err := conn.Send("MULTI")
	if err != nil {
		return err
	}
	err = conn.Send("SET", token, b)
	if err != nil {
		return err
	}
	_, err = conn.Do("EXEC")
	return err
}

func (r *RedisStore) Delete(token string) error {
	conn := r.pool.Get()
	defer conn.Close()

	_, err := conn.Do("DEL", token)
	return err
}
